package com.pay.paytoken.activity.lock;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pay.paytoken.R;
import com.pay.paytoken.base.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import apiUtils.models.AccountStateModel;
import appUtils.AppUtil;
import appUtils.CustomAlertDoubleBtnDialog;
import appUtils.HiddenRule;
import appUtils.SharedPreferencesManager;
import appUtils.ToastUtil;
import butterknife.Bind;
import butterknife.OnClick;

import static appUtils.SharedPreferencesManager.LOCK_FIRST;
import static appUtils.SharedPreferencesManager.VERIFY_PHONE;

/**
 * Created by Administrator on 2017/7/17.
 */

public class DigitalSetLockActivity extends BaseActivity implements TextWatcher {
    private static final int REQUEST_FOCUS = 0x1;
    private static final int SECOND_VIEW = 0x1 << 1;
    private static final int FIRST_VIEW = 0x1 << 2;
    private static final int DISMISS_DIALOG = 0x1 << 3;
    private static final int FINISH = 0x1 << 4;
    private final List<TextView> mNums = new ArrayList<>();
    @Bind(R.id.layout_title_textName)
    TextView mTitleTv;
    @Bind(R.id.layout_title_ivSecond)
    TextView mRightTv;
    @Bind(R.id.activity_set_lock_digital_remark_tv)
    TextView mRemarkTv;
    @Bind(R.id.activity_set_lock_digital_et)
    EditText mDigitalEt;
    @Bind(R.id.num_1)
    TextView mNum1;
    @Bind(R.id.num_2)
    TextView mNum2;
    @Bind(R.id.num_3)
    TextView mNum3;
    @Bind(R.id.num_4)
    TextView mNum4;
    @Bind(R.id.num_5)
    TextView mNum5;
    @Bind(R.id.num_6)
    TextView mNum6;
    private CustomAlertDoubleBtnDialog mDialog;
    private String mPass;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case REQUEST_FOCUS:
                    mDigitalEt.requestFocus();
                    break;
                case SECOND_VIEW:
                    setSecondView();
                    break;
                case FIRST_VIEW:
                    setFirstView();
                    break;
                case DISMISS_DIALOG:
                    if (mDialog != null)
                        mDialog.dismiss();
                    break;
                case FINISH:
                    finish();
                    break;
            }
        }
    };
    private long mFirstTime = 0;

    @Override
    public int setView() {
        return R.layout.activity_set_lock_digital;
    }

    @Override
    public void initData(Bundle savedInstanceState) {

    }

    @Override
    public void initView() {
        mRightTv.setVisibility(View.INVISIBLE);
        if (mSharedPreferencesManager.readBoolean(LOCK_FIRST, true)) {
            initFirstDialog();
            mSharedPreferencesManager.saveBoolean(LOCK_FIRST, false);
        }
        mTitleTv.setText(R.string.unlock_pass);
        mDigitalEt.addTextChangedListener(this);
        mNums.add(mNum1);
        mNums.add(mNum2);
        mNums.add(mNum3);
        mNums.add(mNum4);
        mNums.add(mNum5);
        mNums.add(mNum6);
        setFirstView();
        mHandler.sendEmptyMessage(REQUEST_FOCUS);
        mDigitalEt.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            }
        });
    }

    private void initFirstDialog() {
        mDialog = new CustomAlertDoubleBtnDialog(this);
        mDialog.setMsg(String.format(getString(R.string.welcome_back_please_set_lock_format), getUserName()));
        mDialog.hideTitle();
        mDialog.hideBtnLayout();
        mDialog.setCanceledOnTouchInside(true);
        mDialog.setCancelAble(false);
        mDialog.showDialog();
        mHandler.sendEmptyMessageDelayed(DISMISS_DIALOG, 3000);
    }

    private String getUserName() {
        String bindListStr = mSharedPreferencesManager.readString(SharedPreferencesManager.BINDING_LIST, "");
        if (!TextUtils.isEmpty(bindListStr)) {
            List<AccountStateModel> model = new Gson().fromJson(bindListStr, new TypeToken<List<AccountStateModel>>() {
            }.getType());
            return new HiddenRule().accountCommonHidden(model.get(0).getUserAccount());
        }
        return "**";
    }

    protected void setFirstView() {
        clearNumsBG();
        mPass = "";
        if (LockManager.getInstance().getLockAble()) {
            mRemarkTv.setText(R.string.please_enter_new_password_unlock);
        } else {
            mRemarkTv.setText(R.string.please_enter_unlock_pass);
        }
        mDigitalEt.setText("");
    }

    private void setSecondView() {
        clearNumsBG();
        if (LockManager.getInstance().getLockAble()) {
            mRemarkTv.setText(R.string.please_enter_pass_again);
        } else {
            mRemarkTv.setText(R.string.please_enter_unlock_pass_again);
        }
        mDigitalEt.setText("");
    }

    private void clearNumsBG() {
        for (TextView num : mNums) {
            num.setBackgroundResource(R.drawable.background_digital_lock_circle_unselected);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!LockManager.getInstance().getLockAble()) {
                if (System.currentTimeMillis() - mFirstTime > 2000) {
                    ToastUtil.showLong(R.string.again_according_to_exit_program);
                    mFirstTime = System.currentTimeMillis();
                } else {
                    AppUtil.getInstance().exit();
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        digitalChange(s.length());
    }

    private void digitalChange(int length) {
        if (length > 6) {
            return;
        }
        for (int i = 0; i < length; i++) {
            mNums.get(i).setBackgroundResource(R.drawable.background_digital_lock_circle_selected);
        }
        if (length == 6) {
            if (TextUtils.isEmpty(mPass)) {
                mPass = mDigitalEt.getText().toString();
                mHandler.sendEmptyMessageDelayed(SECOND_VIEW, 300);
            } else {
                if (mPass.equals(mDigitalEt.getText().toString())) {
                    if (LockManager.getInstance().getLockAble()) {
                        ToastUtil.showShort(R.string.change_pass_success);
                    } else {
                        ToastUtil.showShort(R.string.set_pass_success);
                    }
                    LockManager.getInstance().saveDigitalPass(mPass);
                    mHandler.sendEmptyMessageDelayed(FINISH, 500);
                } else {
                    ToastUtil.showLong(R.string.password_input_error_please_enter_again);
                    mHandler.sendEmptyMessageDelayed(FIRST_VIEW, 500);
                }
            }
        } else {
            mNums.get(length).setBackgroundResource(R.drawable.background_digital_lock_circle_unselected);
        }
    }

    @OnClick(R.id.layout_title_iv_left)
    protected void cancel() {
        if (!LockManager.getInstance().getLockAble() && !mSharedPreferencesManager.readBoolean(VERIFY_PHONE, true)) {
            ToastUtil.showShort(R.string.please_set_up_unlock_pass);
        } else {
            finish();
        }
    }
}
